

#import "HLNavigationController.h"

@interface HLNavigationController ()<UIGestureRecognizerDelegate,UINavigationControllerDelegate>

@end

@implementation HLNavigationController


- (void)viewDidLoad
{
    [super viewDidLoad];
    _navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationBar];
    //侧滑返回手势代理
    self.interactivePopGestureRecognizer.delegate = self;
    self.delegate = self;
}




//找出导航栏底部横线
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}



//push
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    //push的时候隐藏底部条
    if(self.viewControllers.count > 0){
        viewController.hidesBottomBarWhenPushed = YES;
        
        UIImage *image = [UINavigationBar appearance].backIndicatorTransitionMaskImage;
        //用leftBarButtonItem自定义返回按钮后, 侧滑手势会失效.
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(NavBackBtnClick)];
        
        //在push动画发生的时候, 禁止滑动手势
        self.interactivePopGestureRecognizer.enabled = NO;
        
    }
    [super pushViewController:viewController animated:animated];
}


//pop
- (void)NavBackBtnClick
{
    [self popViewControllerAnimated:YES];
}




#pragma mark--UINavigationControllerDelegate
//push完成
- (void)navigationController:(UINavigationController *)navigationController
       didShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animate
{
    //控制器入栈之后,启用手势识别
    if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]){
        self.interactivePopGestureRecognizer.enabled = YES;
    }
}



#pragma mark--UIGestureRecognizerDelegate
//让手势生效
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (self.viewControllers.count <= 1 ) {
        return NO;
    }
    return YES;
}


//允许同时响应多个手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:
(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}


//禁止响应手势的是ViewController中scrollView跟着滚动
//这个方法返回YES，第一个和第二个互斥时，第二个会失效
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldBeRequiredToFailByGestureRecognizer:
(UIGestureRecognizer *)otherGestureRecognizer
{
    return [gestureRecognizer isKindOfClass:
            UIScreenEdgePanGestureRecognizer.class];
}


@end
